package com.retaileye.rescanlib;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.zxing.client.android.Intents;
import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;

public class ReScanSDK {

    private static final ReScanSDK reScanSDK = new ReScanSDK();
    private ActivityResultLauncher<ScanOptions> barcodeLauncher;

    private ReScanSDK() {}

    public static ReScanSDK getInstance() {
        return reScanSDK;
    }

    public void init(@NonNull final AppCompatActivity activity, @NonNull final IReScanResult reScanResult) {
        barcodeLauncher = activity.registerForActivityResult(new ScanContract(),
                result -> {
                    if(result.getContents() == null) {
                        Intent originalIntent = result.getOriginalIntent();
                        if (originalIntent == null) {
                            Log.d("MainActivity", "Cancelled scan");
                            reScanResult.onCancel();
//                            Toast.makeText(activity, "Cancelled", Toast.LENGTH_LONG).show();
                        } else if(originalIntent.hasExtra(Intents.Scan.MISSING_CAMERA_PERMISSION)) {
                            Log.d("MainActivity", "Cancelled scan due to missing camera permission");
//                            Toast.makeText(activity, "Cancelled due to missing camera permission", Toast.LENGTH_LONG).show();
                            reScanResult.onPermissionRestricted();
                        }
                    } else {
                        Log.d("MainActivity", "Scanned");
//                        Toast.makeText(activity, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                        reScanResult.onSuccess(result.getContents());
                    }
                });
    }

    public void startBarScan(@NonNull final AppCompatActivity activity, @NonNull final IReScanResult reScanResult) {
        ScanOptions options = new ScanOptions();
        options.setCaptureActivity(AnyOrientationCaptureActivity.class);
        options.setOrientationLocked(false);
        barcodeLauncher.launch(options);
    }

    public interface IReScanResult {
        void onCancel();
        void onPermissionRestricted();
        void onSuccess(String content);
    }
}
